<template>
  <div>
    <RatingCycleSelector
      v-model="filter.round"
      :rating-type="data.period"
      :data-name.sync="filter.ratingDesc"
    />
    <el-table v-loading="loading" :data="list">
      <el-table-column label="表彰单位">
        <template slot-scope="{row}">
          <Company :id="row.companyCode" />
        </template>
      </el-table-column>
      <el-table-column v-for="column in data.children" :key="column.id" :label="column.name">
        <template slot-scope="{row}">
          <div v-if="children_info[column.id] && children_info[column.id][row.id]">
            <Company
              v-if="reward_types_dict[column.id].targetType===1"
              :id="children_info[column.id][row.id].targetCompany"
            />
            <User v-else :userid="children_info[column.id][row.id].targetUserId" />
          </div>
          <div v-else>无</div>
        </template>
      </el-table-column>
      <el-table-column width="40">
        <template slot-scope="{row}">
          <el-button type="text" icon="el-icon-delete" @click="handleRemove(row)" />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { RewardRecordList, RewardContentInfo } from '@/api/zzxt/reward'
import { debounce, arrayToTree } from '@/utils'
export default {
  name: 'RewardList',
  components: {
    RatingCycleSelector: () =>
      import('@/views/MemberRate/RatingTypeOption/RatingCycleSelector'),
    Company: () => import('@/components/Company/CompanyFormItem'),
    User: () => import('@/components/User/UserFormItem')
  },
  props: {
    data: { type: Object, default: null },
    round: { type: Number, default: 0 }
  },
  data: () => ({
    list: null,
    loading: false,
    filter: {
      round: 0,
      ratingDesc: null
    },
    children_info: {} // 用于缓存名册信息
  }),
  computed: {
    requireRefresh() {
      return debounce(() => {
        this.refresh()
      }, 2e2)
    },
    reward_types_dict() {
      const children = this.data.children
      const dict = {}
      children.map(i => {
        dict[i.id] = i
      })
      dict[this.data.id] = this.data
      return dict
    }
  },
  watch: {
    'data.id': {
      handler(val) {
        this.requireRefresh()
      },
      immediate: true
    },
    filter: {
      handler(val) {
        if (!val) return
        this.requireRefresh()
        this.$emit('update:round', val.round)
      },
      deep: true
    }
  },
  methods: {
    handleRemove(row) {
      this.$confirm(`确定删除表彰记录吗？`).then(() => {
        this.loading = true
        const children = row.children.map(i => i.id)
        children.push(row.id) // 仅适用于单层子层级
        const actions = children.map(id =>
          RewardContentInfo({ id, isRemoved: true })
        )
        Promise.all(actions)
          .then(() => {
            this.$message.success('已删除')
          })
          .finally(() => {
            this.loading = false
            this.$emit('requireRefresh')
          })
      })
    },
    refresh() {
      this.loading = true
      const d = this.data
      const rewardId = d.id
      RewardRecordList(Object.assign({ rewardId }, this.filter))
        .then(data => {
          this.list = arrayToTree(
            data.list,
            i => i.id,
            i => i.parents[i.parents.length - 1]
          )
          this.sync_chilren_dict()
        })
        .finally(() => {
          this.loading = false
        })
    },
    sync_chilren_dict() {
      const dict = {}
      const { list } = this
      list.map(i => {
        const item_children = i.children
        item_children.map((prop, index) => {
          const { rewardId } = prop
          if (!dict[rewardId]) dict[rewardId] = {}
          dict[rewardId][i.id] = prop
        })
      })
      this.$set(this, 'children_info', dict)
    }
  }
}
</script>
